package com.cskaoyan.service.impl;


import com.cskaoyan.mapper.MarketAddressMapper;
import com.cskaoyan.model.MarketAddress;
import com.cskaoyan.model.MarketAddressExample;
import com.cskaoyan.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

@Service
public class AddressServiceImpl implements AddressService {
    @Autowired
    MarketAddressMapper addressMapper;

    @Override
    public MarketAddress selectById(Integer id) {
        //创建example用于查询选中的address
        MarketAddressExample example = new MarketAddressExample();
        if (id == 0) {
            //id为0 就查找默认的address
            example.createCriteria().andDeletedEqualTo(false)
                    .andIsDefaultEqualTo(true);
            example.setOrderByClause("add_time desc");
            //条件查询
            List<MarketAddress> addressList = addressMapper.selectByExample(example);
            //不为空就返回默认地址中的第一个(虽然不合理但可能有多个默认地址，数据库数据的原因)，为空就返回null表示没有查到默认地址
            return !addressList.isEmpty() ? addressList.get(0) : null;
        } else {
            //id不为0就直接通过id(主键)查找出这个地址
            return addressMapper.selectByPrimaryKey(id);
        }
    }

    /**
     * 该方法传入0则查找user默认的收货地址，否则返回address
     *
     * @param i
     * @param addressId
     * @return
     */
    @Override
    public MarketAddress findAddrById(Integer userId, Integer addressId) {
        MarketAddressExample addressExample = new MarketAddressExample();
        if (addressId.equals(0)) {
            addressExample.createCriteria().andDeletedEqualTo(false).andUserIdEqualTo(userId).andIsDefaultEqualTo(true);
            List<MarketAddress> marketAddressList = addressMapper.selectByExample(addressExample);

            return marketAddressList != null && !marketAddressList.isEmpty() ? marketAddressList.get(0) : new MarketAddress();

        } else {

            addressExample.createCriteria().andDeletedEqualTo(false).andUserIdEqualTo(userId).andIdEqualTo(addressId);
            List<MarketAddress> marketAddressList = addressMapper.selectByExample(addressExample);

            return marketAddressList != null && !marketAddressList.isEmpty() ? marketAddressList.get(0) : new MarketAddress();

        }
    }

    @Override
    public List<MarketAddress> list(Integer userId) {
        MarketAddressExample example = new MarketAddressExample();
        example.createCriteria().andUserIdEqualTo(userId)
                .andDeletedEqualTo(false);
        //默认地址排在第一位
        //在满足第一个排序条件的基础上，继续按照add_Time字段进行降序排序
        example.setOrderByClause("is_default desc,add_Time desc");
        List<MarketAddress> addressList = addressMapper.selectByExample(example);
        return addressList;
    }

    @Override
    public Integer saveAddress(Integer userId, MarketAddress address) {
        Date current = new Date();
        //1.id==0时是新增
        Integer id = address.getId();
        if (id == 0) {
            ensureUniqueDefaultAddress(userId, address, current);
            address.setId(null);
            address.setUserId(userId);
            address.setAddTime(current);
            address.setUpdateTime(current);
            addressMapper.insertSelective(address);
            //主键自增并返回
            return address.getId();
        }

        //2.id>0时是更新
        address.setUpdateTime(current);
        ensureUniqueDefaultAddress(userId, address, current);
        //选择性更新
        address.setId(id);
        addressMapper.updateByPrimaryKeySelective(address);
        return id;
    }
    @Override
    public Integer delete(Integer userId, Integer addressId) {
        int affectedRows = addressMapper.deleteByPrimaryKey(addressId);
        return affectedRows;
    }

    @Override
    public MarketAddress getDefaultAddress(Integer userId) {
        MarketAddressExample example = new MarketAddressExample();
        example.createCriteria().andUserIdEqualTo(userId)
                .andIsDefaultEqualTo(true)
                .andDeletedEqualTo(false);
        List<MarketAddress> addressList = addressMapper.selectByExample(example);
        return addressList != null && addressList.size() == 1 ? addressList.get(0) : null;
    }

    private void ensureUniqueDefaultAddress(Integer userId, MarketAddress address, Date current) {
        //新增时/更新时要保证默认地址的唯一性
        if (address.getIsDefault()) {
            //将用户--->其它地址的is_deefault为true的设为false
            MarketAddressExample example = new MarketAddressExample();
            example.createCriteria().andUserIdEqualTo(userId)
                    .andIsDefaultEqualTo(true)
                    .andDeletedEqualTo(false);
            MarketAddress record = MarketAddress.builder()
                    .isDefault(false)
                    .updateTime(current)
                    .build();
            addressMapper.updateByExampleSelective(record, example);
        }
    }
}
